//
//  ScanVerifyViewController.swift
//  NGTC_iOS
//
//  Created by Mr.wang on 2018/12/24.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import Moya
import AVFoundation

class ScanVerifyViewController: BaseUIViewController {

    let flushButton = UIButton()
    let foreGroundImageView = UIImageView()
    
    let scanWidth = SCREEN_WIDTH * 0.8
    let scanHeight = SCREEN_WIDTH * 0.5
    var scanRect: CGRect {
        return CGRect(x: (SCREEN_WIDTH - scanWidth) * 0.5, y: (SCREEN_HEIGHT - scanHeight) * 0.5, width: scanWidth, height: scanHeight)
    }
    var barcode: String = ""
    
    var scanUnit: ScanUnit?
    
    let longitude: String?
    let latitude: String?
    let address: String?
    
    typealias SuccessClosure = (String) -> ()
    var scanComplete: SuccessClosure?
    
    init(longitude: String? = nil, latitude: String? = nil, address: String? = nil) {
        self.longitude = longitude
        self.latitude = latitude
        self.address = address
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupView()
        
        PermissionProvider.request(.camera, success: { [weak self] in
            self?.setupCamera()
        }) { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        scanUnit?.startRunning()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        scanUnit?.stopRunning()
    }
    
    func setupView() {
        self.navigationItem.title = "扫码验证".localized
        self.view.backgroundColor = UIColor.black
        
        let path = UIBezierPath(roundedRect: self.view.bounds, cornerRadius: 0)
        let circlePath = UIBezierPath(roundedRect: scanRect, cornerRadius: 0)
        path.append(circlePath)
        path.usesEvenOddFillRule = true
        
        let fillLayer = CAShapeLayer()
        fillLayer.path = path.cgPath
        fillLayer.fillRule = .evenOdd
        fillLayer.fillColor = UIColor.black.cgColor
        fillLayer.opacity = 0.4
        self.view.layer.addSublayer(fillLayer)
        
        let backgroundImageView = UIImageView()
        backgroundImageView.frame = scanRect
        backgroundImageView.image = UIImage.init(named: "qrcode_image")
        backgroundImageView.clipsToBounds = true
        self.view.addSubview(backgroundImageView)
        
        foreGroundImageView.frame = CGRect(x: 20, y: 0, width: backgroundImageView.width - 40, height: 4)
        foreGroundImageView.image = UIImage.init(named: "scan_line")
        backgroundImageView.addSubview(foreGroundImageView)
        setForegroundImageAnimation()
        
        flushButton.isHidden = true
        flushButton.setImage(UIImage.init(named: "flush_close"), for: .normal)
        flushButton.setImage(UIImage.init(named: "flush_open"), for: .selected)
        flushButton.addTarget(self, action: #selector(flushButtonClick), for: .touchUpInside)
        self.view.addSubview(flushButton)
        flushButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(foreGroundImageView.snp.bottom).offset(-5)
            make.centerX.equalTo(self.view.snp.centerX)
            make.height.width.equalTo(40)
        }
        
        let iconLabel = IconLabel()
        iconLabel.image = UIImage.init(named: "scan_info")
        iconLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        iconLabel.textColor = #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        let text = NSMutableAttributedString.init(string: "请扫描条形码进行验证".localized)
        text.setTextColor(.white, text: "条形码".localized)
        iconLabel.attributedText = text
        self.view.addSubview(iconLabel)
        iconLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(18)
            make.bottom.equalTo(-UIApplication.shared.bottomSafeDistance - 60)
        }
    }
    
    func analyzeCode(_ code: String) {
        self.barcode = code
        
        ApiManager.scanVerify(code, longitude: longitude ?? "", latitude: latitude ?? "", address: address ?? "").request()
            .errorWhenCodeNot200()
            .dataModelMap(CheckModel.self)
            .trackingLoading()
            .subscribe(onNext: { [weak self] (result) in
                if result.result.isSuccess {
                    let vc = NFCScanViewController.init(barcode: code, longitude: self?.longitude, latitude: self?.latitude, address: self?.address)
                    vc.scanComplete = self?.scanComplete
                    self?.navigationController?.pushTo(vc, remove: 1)
                } else {
                    self?.navigationController?
                        .pushTo(FailureViewController(psrCheckId: result.id, barCode: code, errorMessage: result.checkMsg, errorCode: result.code), remove: 1)
                }
                }, onError: { [weak self] _ in
                self?.scanUnit?.startRunning()
            }).disposed(by: rx.disposeBag)
    }
    
    @objc func flushButtonClick() {
        scanUnit?.changeFlush()
    }
    
    func setupCamera() {
        scanUnit = ScanUnit.init(scanRect: scanRect, on: self.view)
        
        scanUnit?.flushButtonHide
            .bind(to: flushButton.rx.isHidden)
            .disposed(by: rx.disposeBag)
        
        scanUnit?.flushOn
            .bind(to: flushButton.rx.isSelected)
            .disposed(by: rx.disposeBag)
        
        scanUnit?.completeHandler = { [weak self] code in
            self?.analyzeCode(code)
        }
    }
    
    func setForegroundImageAnimation() {
        foreGroundImageView.alpha = 1
        foreGroundImageView.y = 10
        
        UIView.animate(withDuration: 2, animations: { [weak self] in
            guard let self = self else { return }
            self.foreGroundImageView.y = self.scanHeight - 14
        }) { [weak self] (_) in
            guard let self = self else { return }
            UIView.animate(withDuration: 1, animations: {
                self.foreGroundImageView.alpha = 0
            }) { (_) in
                self.setForegroundImageAnimation()
            }
        }
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .clearColor
    }
    
}
